package com.koro.tool;

import com.koro.entity.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class SecurityJwtUtil {
    //一天过期
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    //解密jwt-token的密钥
    private static final String secret = "koro";

    /**
     * 生成token
     */
    public static String sign(String username, String loginType) {
        return Jwts.builder()
                .claim("username", username)
                .claim("loginType", loginType)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 根据token解密出用户名
     */
    public String getUsername(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }

    /**
     * 根据token解密出登录类型
     */
    public String getLoginType(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return (String) claims.get("loginType");
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }
    /**
     * 根据token解密出过期时间
     */
    public Date getExpiredDate(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return claims.getExpiration();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }



    /**
     * 判断token是否已经过期
     */
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDate(token);
        return expiredDate.before(new Date());
    }
    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }
    /**
     * 验证token与数据库中token是否一致
     */
    public boolean validateToken(String token, LoginUser loginUser) {
        String username = getUsername(token);
        assert username != null;
        return username.equals(loginUser.getUsername()) && !isTokenExpired(token);
    }
}
